package test5.lupeng.jf.com.teamdemo.activitys;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import javax.security.auth.login.LoginException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import test5.lupeng.jf.com.teamdemo.R;
import test5.lupeng.jf.com.teamdemo.bean.RequestCollect;
import test5.lupeng.jf.com.teamdemo.bean.RequestSend;
import test5.lupeng.jf.com.teamdemo.bean.response.ResponseResult;
import test5.lupeng.jf.com.teamdemo.untils.Appconfig;
import test5.lupeng.jf.com.teamdemo.untils.HTTPUtils;

//文章界面
public class TitleActivity extends AppCompatActivity {

    private static final String TAG ="TitleActivity" ;
    private WebView webView;
    private LinearLayout write;
    private LinearLayout book;
    private LinearLayout star;
    private TextView messageNumber;
    private TextView starNumber;
    private String content;
    private String articleId;
    private int articleType;
    private Boolean isLogin;
    private int count1;
    private int count2;
    private IntentFilter intentFilter;
    private LocalBroadcastManager manager;
    private TitleReceiver receiver;
    private String newuserId;
    //判断收藏状态；
    private int count3 = 0;
    private ImageView newStar;
    private Boolean isLikeSizeStatus;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_title);
        initView();

        SharedPreferences sp = getSharedPreferences("LoginStatus", MODE_PRIVATE);
        isLogin = sp.getBoolean("isLogin", false);
        //Log.e(TAG, "测试底部导航点击是否登录 "+ isLogin);

        SharedPreferences sp2 = getSharedPreferences("config", MODE_PRIVATE);
        newuserId = sp2.getString("objectId","0");

        articleId = getIntent().getStringExtra("articleId");
        articleType = getIntent().getIntExtra("articleType", 0);
        content = getIntent().getStringExtra("content");
        count1 = getIntent().getIntExtra("count1",0);
        count2 = getIntent().getIntExtra("count2",0);
        count3 = count2;


        messageNumber.setText(count1+"");
        starNumber.setText(count2+"");

        intentFilter = new IntentFilter();
        intentFilter.addAction("SEND_MESSAGE");
        manager = LocalBroadcastManager.getInstance(this);
        receiver = new TitleReceiver();
        manager.registerReceiver(receiver,intentFilter);



        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(content);

        //拿到首页的收藏状态
        isLikeSizeStatus = getIntent().getBooleanExtra("isLikeSizeStatus",false);


        if (isLikeSizeStatus) {
            newStar.setBackgroundColor(Color.GRAY);
        }else{
            newStar.setBackgroundColor(Color.WHITE);
        }

    }

    //笔的点击事件
    public void checkLogin(View view) {

        //登录状态下
        if(isLogin){

            Intent intent = new Intent(TitleActivity.this, TalkTitleActivity.class);
            intent.putExtra("articleId", articleId);
            intent.putExtra("articleType", articleType);
            startActivityForResult(intent, 7);

        }else{
            showDiaLog();
        }

    }

    //书的点击事件
    public void clickBook(View view){
        if (isLogin) {

            Intent intent = new Intent(TitleActivity.this, TitleCheckActivity.class);
            intent.putExtra("articleId", articleId);
            intent.putExtra("articleType", articleType);
            startActivityForResult(intent, 9);

        }else{
            showDiaLog();
        }

    }

    //收藏夹点击
    public void clickStar(View view) {
        if(isLogin){

            //收藏或取消方法；
              CollectTitle();

        }else{
            showDiaLog();
        }



    }


    //取消收藏文章的方法
    public void CollectTitle(){

        RequestCollect collect = new RequestCollect(articleId, articleType, newuserId);
        String url = "https://leancloud.cn:443/1.1/functions/addInformationCollection";
        Request request = HTTPUtils.requestPost(collect, url);
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i(TAG, "onResponse: "+result);
//                ResponseResult bean = new Gson().fromJson(result, ResponseResult.class);
//                String s = bean.getResult().getMess();
//                System.out.println(s);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(isLikeSizeStatus){
                            //收藏状态
                            Toast.makeText(TitleActivity.this, "取消成功！", Toast.LENGTH_SHORT).show();
                            starNumber.setText(count3-1+""); //1
                            count3 = count3 - 1;
                            isLikeSizeStatus = false;
                            newStar.setBackgroundColor(Color.WHITE);
                        }else{
                            Toast.makeText(TitleActivity.this, "收藏成功！", Toast.LENGTH_SHORT).show();
                            starNumber.setText(count3+1+""); //2
                            count3 = count3+1;
                            isLikeSizeStatus = true;
                            newStar.setBackgroundColor(Color.GRAY);
                        }
                    }
                });


//                if(s.equals("收藏成功")){
//                    //值+1
//                    isCollected = true;
//
//                }else{
//                    //值-1
//                    isCollected = false;
//                }
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        if(isCollected){
//                            starNumber.setText(count3+"");
//                            Toast.makeText(TitleActivity.this, "收藏成功！", Toast.LENGTH_SHORT).show();
//                            isLikeSizeStatus = true;
//                            newStar.setBackgroundColor(Color.GRAY);
//                        }else{
//                            starNumber.setText(count4+"");
//                            Toast.makeText(TitleActivity.this, "取消成功！", Toast.LENGTH_SHORT).show();
//                            isLikeSizeStatus = false;
//                            newStar.setBackgroundColor(Color.WHITE);
//                        }
//
//                    }
//                });



            }
        });
    }


    //弹出框
    public void showDiaLog(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("提示");
        dialog.setMessage("该操作需要登录，是否登录？");
        dialog.setCancelable(false);
        dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(TitleActivity.this, LoginActivity.class);
                startActivityForResult(intent, 8);
            }
        });
        dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.show();

    }

    public void initView(){
        //发送评论
        write = (LinearLayout) findViewById(R.id.write);

        //查看评论列表
        book = (LinearLayout) findViewById(R.id.book);
        messageNumber = (TextView) findViewById(R.id.messageNumber);

        //收藏
        star = (LinearLayout) findViewById(R.id.star);

        newStar = (ImageView) findViewById(R.id.newStar);

        starNumber = (TextView) findViewById(R.id.starNumber);

    }

    public void newReturn(View view) {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 7:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this,"评论提交成功！",Toast.LENGTH_LONG).show();
                }
                break;
     }
    }

    //自定义广播
    public class TitleReceiver extends BroadcastReceiver{
        int i = 1;

        @Override
        public void onReceive(Context context, Intent intent) {

            messageNumber.setText((count1+i)+"");
            i++;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        manager.unregisterReceiver(receiver);
    }

    //监听Back键按下的事件
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        EventBus.getDefault().post("返回成功！");
    }
}
